<?php

namespace app\home\controller;

use app\home\model\Course;
use app\home\model\Apply;
use think\Request;
use app\home\model\Coursetype;

class  Courses2 extends Base
{
    //查询专业大类
    public function Course_type(Request $request){
        $examtype_id = $request->post("examtype_id");
        //查询报考类型下的专业大类列表
        $coursetype = Coursetype::where(['examtype_id'=>$examtype_id])->order('id','asc')->select();
        $resArr = collection($coursetype)->toArray();
        return json($resArr);
    }

    //查询第一个专业大类的名称
    public function Course_type_name(Request $request){
           $res =  Coursetype::where(['examtype_id'=>$request->post('examtype_id')])->order('id',"asc")->find();
           return $res['name'];
    }
    //查询第一个专业大类的id
    public function Course_type_id(Request $request){
        $res =  Coursetype::where(['examtype_id'=>$request->post('examtype_id')])->order('id',"asc")->find();
        return $res['id'];
    }


    //查询当前专业大类下的所有专业
    public function index(Request $request)
    {
      //接收专业大类的id
      $data = $request->post('coursetype_id');
      $res = Course::where('typeid',$data)->order("sort","asc")->select();
      $resArr = collection($res)->toArray();
      //查询当前grade不同专业报名的数量
      $applys = Apply::where(['grade'=>$request->post('grade')])->field("major_id,count(*) as c")->group("major_id")->select();
      $arr = [];
      foreach($applys as $val){
        $arr[$val['major_id']] = $val['c'];
      }
//      var_dump($resArr);
      foreach($resArr as $key=>$val){
        $resArr[$key]['apply_number'] = array_key_exists($val['id'],$arr) ? $arr[$val['id']] : 0;
        $resArr[$key]['name'] = $val['name']."(剩余".($val['number'] - $resArr[$key]['apply_number'])."个名额)";
      }
      return json($resArr);
    }

    //查询当前专业大类下的第一个专业
    public function first(Request $request)
    {
        //接收查询的专业大类id
        $data = $request->post("coursetype_id");
      $res = Course::where('typeid',$data)->order("sort","asc")->find();
      $apply_number = Apply::where(["grade"=>date("Y",time()),"major_id"=>$res["id"],'coursetype_id'=>$data])->field("count(*) as c")->find()->toArray();
      $arr = [
        "name"=>$res["name"],
        "number"=> $res["number"]-$apply_number['c'] <=0 ? 0 :$res["number"]-$apply_number['c']
      ];
      return json($arr);
    }

    //查询当前专业大类下的第一个专业的id
    public function first_id(Request $request)
    {
        //接收查询的专业大类id
        $data = $request->post("coursetype_id");
        $res = Course::where('typeid',$data)->order("sort","asc")->find();
        $apply_number = Apply::where(["grade"=>date("Y",time()),"major_id"=>$res["id"],'coursetype_id'=>$data])->field("count(*) as c")->find()->toArray();
        $arr = [
            "name"=>$res["name"],
            "number"=> $res["number"]-$apply_number['c'] <=0 ? 0 :$res["number"]-$apply_number['c']
        ];
        return json($arr);
    }

    //查询所有的专业分类
}
